#
# adapted from http://coderrr.wordpress.com/2008/10/21/when-to-use-readpartial-instead-of-read-in-ruby/
#
class IO
  # "drains" a socket, returning immediately with whatever data is available. If
  # there is no data available it will wait until any amount of data becomes
  # available and return it immediately.
  def drain(data = nil)
    while buf = readpartial_rescued(1024)
      data << buf  if data
      yield buf if block_given?
    end
    data
  end

  private

  def readpartial_rescued(size)
    readpartial(size)
  rescue EOFError
    nil
  end
end